package com.fdb.efp.nls.service.impl;

import com.fdb.basic.framework.core.base.FrameworkService;
import com.fdb.efp.nls.service.dao.AccLoanDao;
import com.fdb.efp.nls.service.dao.GzBankSettleRepayDetailFileTempDao;
import com.fdb.efp.nls.service.dao.LoanSettleRepayDetailDao;
import com.fdb.efp.nls.service.dao.SettleDetailAccountTempDao;
import com.fdb.efp.nls.service.domain.AccLoan;
import com.fdb.efp.nls.service.domain.GzBankSettleRepayDetailFileTemp;
import com.fdb.efp.nls.service.domain.LoanSettleRepayDetail;
import com.fdb.efp.nls.service.domain.SettleDetailAccountTemp;
import com.fdb.efp.nls.service.facade.AccoutErroTempService;
import com.fdb.efp.nls.service.facade.LoanSettleRepayDetailService;
import com.fdb.efp.nls.service.vo.LoanSettleRepayDetailVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * ServiceImpl: 马上理赔还款明细表
 * <p>
 * 
 * @author cyj
 * @date 2018-12-27
 */
@Service("loanSettleRepayDetailService")
public class LoanSettleRepayDetailServiceImpl implements LoanSettleRepayDetailService, FrameworkService {

	private static Logger logger = LoggerFactory.getLogger(LoanSettleRepayDetailServiceImpl.class);

	@Autowired
	private LoanSettleRepayDetailDao loanSettleRepayDetailDao;
	@Autowired
	private GzBankSettleRepayDetailFileTempDao gzBankSettleRepayDetailFileTempDao;
	@Autowired
	private SettleDetailAccountTempDao settleDetailAccountTempDao;
	@Autowired
	private AccoutErroTempService accoutErroTempService;
	@Autowired
	private AccLoanDao accLoanDao;

	/**
	 * 同步马上的数据 新增 理赔还款明细表
	 * 
	 * @description:TODO
	 * @date:2018年12月28日 下午3:33:37
	 * @author:cenyj
	 */
	public boolean batchLoanSettleRepayDetailFromMaTxt() throws Exception {
		boolean rs = false;
		try {

			// 先 对账表，看是否能对应上
			logger.info("日终批量修改从马上同步过来的临时表数据到还款明细表：");
			// 先校对 对账临时表的记录条数跟同步过来的数据是否一致 如果一致 再批量 把临时表的数据同步到本地
			// 临时表
			List<GzBankSettleRepayDetailFileTemp> list = gzBankSettleRepayDetailFileTempDao.getGzBankSettleRepayDetailFileTempList();
			// 对账临时表列表
			List<SettleDetailAccountTemp> accountList = settleDetailAccountTempDao.getSettleDetailAccountTempList();
			// 对账临时表
			SettleDetailAccountTemp accountTempModel = new SettleDetailAccountTemp();
			// 临时表列表的sum
			Double payPrincipalAmt = list.stream().mapToDouble(GzBankSettleRepayDetailFileTemp::getPayPrincipalAmt).sum();
			Double actualPayPrincipalAmt = list.stream().mapToDouble(GzBankSettleRepayDetailFileTemp::getActualPayPrincipalAmt).sum();
			Double payinterestamt = list.stream().mapToDouble(GzBankSettleRepayDetailFileTemp::getPayInterestAmt).sum();
			Double actualPayInterestAmt = list.stream().mapToDouble(GzBankSettleRepayDetailFileTemp::getActualPayInterestAmt).sum();
			Double payPrincipalPenaltyAmt = list.stream().mapToDouble(GzBankSettleRepayDetailFileTemp::getPayPrincipalPenaltyAmt).sum();
			Double actualPayPrincipalPenaltyAmt = list.stream()
					.mapToDouble(GzBankSettleRepayDetailFileTemp::getActualPayPrincipalPenaltyAmt).sum();
			BigDecimal payPrincipalAmtSum = BigDecimal.valueOf(payPrincipalAmt == null ? 0 : payPrincipalAmt);
			BigDecimal actualPayPrincipalAmtSum = BigDecimal.valueOf(actualPayPrincipalAmt == null ? 0 : actualPayPrincipalAmt);
			BigDecimal payinterestamtSum = BigDecimal.valueOf(payinterestamt == null ? 0 : payinterestamt);
			BigDecimal actualPayInterestAmtSum = BigDecimal.valueOf(actualPayInterestAmt == null ? 0 : actualPayInterestAmt);
			BigDecimal payPrincipalPenaltyAmtSum = BigDecimal.valueOf(payPrincipalPenaltyAmt == null ? 0 : payPrincipalPenaltyAmt);
			BigDecimal actualPayPrincipalPenaltyAmtSum = BigDecimal
					.valueOf(actualPayPrincipalPenaltyAmt == null ? 0 : actualPayPrincipalPenaltyAmt);

			// 對賬裏面的值
			int accountCountTemp = 0;// 对账表记录的条数
			int loanTempDatasize = 0;// 实际同步过来的数据总条数
			if (accountList != null && accountList.size() > 0) {
				accountTempModel = accountList.get(0);
			}
			if (accountTempModel != null) {
				accountCountTemp = accountTempModel.getDataAcount() == null ? 0 : accountTempModel.getDataAcount();
				String tableName = "GzBankSettleRepayDetailFileTemp";
				if (accountTempModel.getPayPrincipalAmtTotal() != payPrincipalAmtSum) {
					String erroMsg = "应还本金总额getPayPrincipalAmtTotal不对";
					String tempTotal = "" + accountTempModel.getPayPrincipalAmtTotal();
					String acountTotal = "" + payPrincipalAmtSum;
					accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");
				}
				if (accountTempModel.getActualPayPrincipalAmtTotal() != actualPayPrincipalAmtSum) {
					String erroMsg = "还款本金总额getActualPayPrincipalAmtTotal不对";
					String tempTotal = "" + accountTempModel.getActualPayPrincipalAmtTotal();
					String acountTotal = "" + actualPayPrincipalAmtSum;
					accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");
				}
				if (accountTempModel.getPayinterestamtTotal() != payinterestamtSum) {
					String erroMsg = "应还利息总额getPayinterestamtTotal不对";
					String tempTotal = "" + accountTempModel.getPayinterestamtTotal();
					String acountTotal = "" + payinterestamtSum;
					accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");
				}
				if (accountTempModel.getActualPayinterestAmtTotal() != actualPayInterestAmtSum) {
					String erroMsg = "还款利息总额getActualPayinterestAmtTotal不对";
					String tempTotal = "" + accountTempModel.getActualPayinterestAmtTotal();
					String acountTotal = "" + actualPayInterestAmtSum;
					accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");
				}
				if (accountTempModel.getPayPrincipalPenaltyAmtTotal() != payPrincipalPenaltyAmtSum) {
					String erroMsg = "应还罚息总额getPayPrincipalPenaltyAmtTotal不对";
					String tempTotal = "" + accountTempModel.getPayPrincipalPenaltyAmtTotal();
					String acountTotal = "" + payPrincipalPenaltyAmtSum;
					accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");
				}
				if (accountTempModel.getActualPayPrincipalPenaltyAmtTotal() != actualPayPrincipalPenaltyAmtSum) {
					String erroMsg = "还款罚息总额getActualPayPrincipalPenaltyAmtTotal不对";
					String tempTotal = "" + accountTempModel.getActualPayPrincipalPenaltyAmtTotal();
					String acountTotal = "" + actualPayPrincipalPenaltyAmtSum;
					accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");
				}

			}
			loanTempDatasize = list.size();
			logger.info("对账表记录的条数loanTempDatasize：" + loanTempDatasize + "实际同步过来的数据总条数loanTempDatasize" + loanTempDatasize);
			if (loanTempDatasize != accountCountTemp) {
				// 如果条数不一样，则记录到erro_msg表
				String erroMsg = "记录条数不对";
				String tableName = "GzBankSettleRepayDetailFileTemp";
				String tempTotal = "" + loanTempDatasize;
				String acountTotal = "" + accountCountTemp;
				accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");
			}

			// 本地表进行修改INSERT
			if (list != null && list.size() > 0) {
				for (GzBankSettleRepayDetailFileTemp fileTemp : list) {
					// 因爲有可能出现我们审批没有通过，但马上放款的数据，所以先判断本地借据表是否有对应的借据号 有再新增
					AccLoan acc_loan = new AccLoan();
					acc_loan.setBillNo(fileTemp.getLoanNo());
					AccLoan accLoan = accLoanDao.queryByPk(acc_loan);
					if (accLoan != null) {
						LoanSettleRepayDetail settleModel = new LoanSettleRepayDetail();
						try {
							/** 还款明细流水号p_l_serial_no */
							settleModel.setPLSerialNo(fileTemp.getPlSerialNo());
							/** 还款计划流水号 */
							settleModel.setPSSerialNo(fileTemp.getPsSerialNo());
							/** 贷款账号 */
							settleModel.setLoanNo(fileTemp.getLoanNo());
							/** 应还日期 */
							settleModel.setPayDate(fileTemp.getPayDate());
							/** 实还日期 */
							settleModel.setActualPayDate(fileTemp.getActualPayDate());
							/** 币种 */
							settleModel.setCurrency(fileTemp.getCurrency());
							/** 应还本金 */
							// 类型不一样BigDecimal double
							settleModel.setPayPrincipalAmt(
									BigDecimal.valueOf(fileTemp.getPayPrincipalAmt() == null ? 0 : fileTemp.getPayPrincipalAmt()));
							/** 实还本金 */
							settleModel.setActualPayPrincipalAmt(BigDecimal
									.valueOf(fileTemp.getActualPayPrincipalAmt() == null ? 0 : fileTemp.getActualPayPrincipalAmt()));

							/** 剩余本金余额 */
							settleModel.setPrincipalBalance(
									BigDecimal.valueOf(fileTemp.getPrincipalBalance() == null ? 0 : fileTemp.getPrincipalBalance()));
							/** 应还利息 */
							settleModel.setPayinterestAmt(
									BigDecimal.valueOf(fileTemp.getPayInterestAmt() == null ? 0 : fileTemp.getPayInterestAmt()));

							/** 实还利息 */
							settleModel.setActualPayInterestAmt(BigDecimal
									.valueOf(fileTemp.getActualPayInterestAmt() == null ? 0 : fileTemp.getActualPayInterestAmt()));
							/** 应还本金罚息 */
							settleModel.setPayPrincipalPenaltyAmt(BigDecimal
									.valueOf(fileTemp.getPayPrincipalPenaltyAmt() == null ? 0 : fileTemp.getPayPrincipalPenaltyAmt()));
							/** 实还本金罚息 */
							settleModel.setActualPayPrincipalPenaltyAmt(BigDecimal.valueOf(
									fileTemp.getActualPayPrincipalPenaltyAmt() == null ? 0 : fileTemp.getActualPayPrincipalPenaltyAmt()));
							/** 应还利息罚息 */
							settleModel.setPayInterestPenaltyAmt(BigDecimal
									.valueOf(fileTemp.getPayInterestPenaltyAmt() == null ? 0 : fileTemp.getPayInterestPenaltyAmt()));
							/** 实还利息罚息 */
							settleModel.setActualPayInterestPenaltyAmt(BigDecimal.valueOf(
									fileTemp.getActualPayInterestPenaltyAmt() == null ? 0 : fileTemp.getActualPayInterestPenaltyAmt()));
							/**
							 * 状态 Status 状态 String 10 "1 正常 2 失效"
							 */
							settleModel.setStatus(fileTemp.getStatus());// 取字典库数据
							/** 实还期次 */
							settleModel.setPeriodno(fileTemp.getPeriodNo());
							int num = insertLoanSettleRepayDetail(settleModel);
							if (num == -1) {
								logger.error("新增数据发生异常!");
								String tableName = "LoanSettleRepayDetail理赔明细表";
								String erroMsg = "";
								String tempTotal = "";
								String acountTotal = "";
								String type = "0";
								String updateDelInster = "新增";
								String no = fileTemp.getLoanNo();
								String eMsg = "新增数据发生异常!";
								accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no,
										eMsg);
							}

						} catch (Exception e) {
							logger.error("新增数据发生异常!", e);
							e.printStackTrace();
							String tableName = "LoanSettleRepayDetail理赔明细表";
							String erroMsg = "";
							String tempTotal = "";
							String acountTotal = "";
							String type = "0";
							String updateDelInster = "新增";
							String no = fileTemp.getLoanNo();
							String eMsg = e.getMessage();
							accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no,
									eMsg);

						}
					} else {
						logger.info("没有对应的借据数据信息!");
						String tableName = "LoanSettleRepayDetail理赔明细表";
						String erroMsg = "";
						String tempTotal = "";
						String acountTotal = "";
						String type = "0";
						String updateDelInster = "新增";
						String no = fileTemp.getLoanNo();
						String eMsg = "没有对应的借据数据信息!";
						accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no, eMsg);
					}
				}

			}
			rs = true;
		} catch (Exception e) {
			logger.error("理赔明细数据发生异常!", e);
			e.printStackTrace();
			String tableName = "LoanSettleRepayDetail理赔明细表";
			String erroMsg = "";
			String tempTotal = "";
			String acountTotal = "";
			String type = "0";
			String updateDelInster = "";
			String no = "";
			String eMsg = e.getMessage();
			accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no,
					eMsg);
		}
		return rs;
	}

	/**
	 * 新增操作
	 */
	public int insertLoanSettleRepayDetail(LoanSettleRepayDetail inLoanSettleRepayDetail) {
		logger.debug("当前新增数据为:" + inLoanSettleRepayDetail.toString());
		int num = 0;
		try {
			num = loanSettleRepayDetailDao.insertLoanSettleRepayDetail(inLoanSettleRepayDetail);
		} catch (Exception e) {
			logger.error("新增数据发生异常!", e);
			num = -1;
		}
		logger.debug("当前新增数据条数为:" + num);
		return num;
	}

	/**
	 * 删除操作
	 */
	public int deleteByPk(LoanSettleRepayDetailVO inLoanSettleRepayDetailVo) {
		logger.debug("当前删除数据条件为:" + inLoanSettleRepayDetailVo);
		int num = 0;
		try {
			LoanSettleRepayDetail loanSettleRepayDetail = new LoanSettleRepayDetail();
			beanCopy(inLoanSettleRepayDetailVo, loanSettleRepayDetail);
			num = loanSettleRepayDetailDao.deleteByPk(loanSettleRepayDetail);
		} catch (Exception e) {
			logger.error("删除数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:" + inLoanSettleRepayDetailVo + "删除的数据条数为" + num);
		return num;
	}

	/**
	 * 更新操作
	 */
	public int updateByPk(LoanSettleRepayDetailVO inLoanSettleRepayDetailVo) {
		logger.debug("当前修改数据为:" + inLoanSettleRepayDetailVo.toString());
		int num = 0;
		try {
			LoanSettleRepayDetail loanSettleRepayDetail = new LoanSettleRepayDetail();
			beanCopy(inLoanSettleRepayDetailVo, loanSettleRepayDetail);
			num = loanSettleRepayDetailDao.updateByPk(loanSettleRepayDetail);
		} catch (Exception e) {
			logger.error("修改数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:" + inLoanSettleRepayDetailVo + "修改的数据条数为" + num);
		return num;
	}

	/**
	 * 查询操作
	 */
	public LoanSettleRepayDetailVO queryByPk(LoanSettleRepayDetailVO inLoanSettleRepayDetailVo) {

		logger.debug("当前查询参数信息为:" + inLoanSettleRepayDetailVo);
		try {
			LoanSettleRepayDetail queryLoanSettleRepayDetail = new LoanSettleRepayDetail();
			beanCopy(inLoanSettleRepayDetailVo, queryLoanSettleRepayDetail);
			LoanSettleRepayDetail queryRslLoanSettleRepayDetail = loanSettleRepayDetailDao.queryByPk(queryLoanSettleRepayDetail);
			if (Objects.nonNull(queryRslLoanSettleRepayDetail)) {
				LoanSettleRepayDetailVO outLoanSettleRepayDetailVo = beanCopy(queryRslLoanSettleRepayDetail, new LoanSettleRepayDetailVO());
				logger.debug("当前查询结果为:" + outLoanSettleRepayDetailVo.toString());
				return outLoanSettleRepayDetailVo;
			} else {
				logger.debug("当前查询结果为空!");
			}
		} catch (Exception e) {
			logger.error("查询数据发生异常!", e);
		}
		return null;
	}

	/**
	 * 查询用户权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<LoanSettleRepayDetailVO> queryAllOwner(LoanSettleRepayDetailVO loanSettleRepayDetailVo) {

		logger.debug("当前查询本人所属数据信息的参数信息为:");
		List<LoanSettleRepayDetailVO> list = null;
		try {
			List<LoanSettleRepayDetail> loanSettleRepayDetails = loanSettleRepayDetailDao.queryAllOwnerByPage(loanSettleRepayDetailVo);
			logger.debug("当前查询本人所属数据信息的结果集数量为:" + loanSettleRepayDetails.size());
			// pageSet(loanSettleRepayDetails, loanSettleRepayDetailVo);
			list = (List<LoanSettleRepayDetailVO>) beansCopy(loanSettleRepayDetails, LoanSettleRepayDetailVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}

		return list;

	}

	/**
	 * 查询当前机构权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<LoanSettleRepayDetailVO> queryAllCurrOrg(LoanSettleRepayDetailVO loanSettleRepayDetailVo) {

		logger.debug("当前查询本人所属机构数据信息的参数信息为:");
		List<LoanSettleRepayDetail> loanSettleRepayDetails = loanSettleRepayDetailDao.queryAllCurrOrgByPage(loanSettleRepayDetailVo);
		logger.debug("当前查询本人所属机构数据信息的结果集数量为:" + loanSettleRepayDetails.size());
		List<LoanSettleRepayDetailVO> list = null;
		try {
			// pageSet(loanSettleRepayDetails, loanSettleRepayDetailVo);
			list = (List<LoanSettleRepayDetailVO>) beansCopy(loanSettleRepayDetails, LoanSettleRepayDetailVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}

		return list;

	}

	/**
	 * 查询当前机构及下属机构权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<LoanSettleRepayDetailVO> queryAllCurrDownOrg(LoanSettleRepayDetailVO loanSettleRepayDetailVo) {

		logger.debug("当前查询本人所属机构及以下数据信息的参数信息为:");
		List<LoanSettleRepayDetail> loanSettleRepayDetails = loanSettleRepayDetailDao.queryAllCurrDownOrgByPage(loanSettleRepayDetailVo);
		logger.debug("当前查询本人所属机构及以下数据信息的结果集数量为:" + loanSettleRepayDetails.size());
		List<LoanSettleRepayDetailVO> list = null;
		try {
			// pageSet(loanSettleRepayDetails, loanSettleRepayDetailVo);
			list = (List<LoanSettleRepayDetailVO>) beansCopy(loanSettleRepayDetails, LoanSettleRepayDetailVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}

		return list;

	}
}
